package com.xywang.controller;

import com.alibaba.fastjson.JSONArray;
import com.mysql.cj.util.StringUtils;
import com.xywang.pojo.Bill;
import com.xywang.pojo.Provider;
import com.xywang.pojo.User;
import com.xywang.service.bill.BillService;
import com.xywang.service.bill.BillServiceImpl;
import com.xywang.service.provider.ProviderService;
import com.xywang.util.Constants;
import com.xywang.util.PageSupport;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletException;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

@Controller
@RequestMapping("jsp")
public class BillController {
    private BillService billServiceImpl;
    private ProviderService providerServiceImpl;
    private PageSupport pageSupport;
    @Autowired
    public void setPageSupport(PageSupport pageSupport) {
        this.pageSupport = pageSupport;
    }
    @Autowired
    public void setProviderServiceImpl(ProviderService providerServiceImpl) {
        this.providerServiceImpl = providerServiceImpl;
    }
    @Autowired
    public void setBillServiceImpl(BillService billServiceImpl) {
        this.billServiceImpl = billServiceImpl;
    }

    @RequestMapping("/billQuery")
    public String billQuery(String queryProductName, String queryProviderId , String queryIsPayment,String pageIndex, Model model){

        // 将前端获取的参数做判断后封装到bill对象中
        Bill bill = new Bill();

        if (StringUtils.isNullOrEmpty(queryProductName)) {
            queryProductName = "";
        }
        bill.setProductName(queryProductName);
        if (StringUtils.isNullOrEmpty(queryIsPayment)) {
            queryIsPayment= String.valueOf(0);
        }
        bill.setIsPayment(Integer.parseInt(queryIsPayment));
        if (StringUtils.isNullOrEmpty(queryProviderId)) {
            queryProviderId= String.valueOf(0);
        }
        bill.setProviderId(Integer.parseInt(queryProviderId));


        // 实现分页
        // 第一次走这个请求，一定是第一页，页面大小固定的
        int pageSize = Constants.PageSize;// 可以把这个写到配置文件中，方便后期修改：
        int currentPageNo=1;
        // 当前‘页’
        if (pageIndex != null) {
            try{
                currentPageNo = Integer.parseInt(pageIndex);
            }catch (Exception e){
                return "../../error";
            }
        }
        // 获取订单总条数 (分页 ：上一页，下一页)
        int userTotalCount = billServiceImpl.getBillCountService(bill);
        // 调用分页算法工具类
        pageSupport.setCurrentPageNo(currentPageNo);
        pageSupport.setPageSize(pageSize);
        pageSupport.setTotalCount(userTotalCount);
        // 总页数 getTotalPageCount()
        int totalPageCount = pageSupport.getTotalPageCount();
        // 控制首页和尾页
        if(currentPageNo<1){
            currentPageNo = 1;
        }else if(currentPageNo>totalPageCount){
            currentPageNo = totalPageCount;
        }

        // 获取供应商列表，输出到前端
        List<Provider> providerList = providerServiceImpl.getProviderListService("", "");

        // 获取订单列表
        List<Bill> billList = billServiceImpl.getBillList(queryProductName,queryProviderId ,queryIsPayment,currentPageNo,pageSize);

        // 像前端发送数据
        model.addAttribute("totalCount",userTotalCount);// 用户总数
        model.addAttribute("currentPageNo",currentPageNo);// 当前页
        model.addAttribute("totalPageCount",totalPageCount);// 总页数

        model.addAttribute("providerList", providerList);
        model.addAttribute("billList", billList);
        model.addAttribute("queryProductName", queryProductName);
        model.addAttribute("queryProviderId", queryProviderId);
        model.addAttribute("queryIsPayment", queryIsPayment);
        return "billList";
    }
    @RequestMapping("/toBillAddPage")
    public String toBillAddPage(){
        return "/billAdd";
    }
    @RequestMapping("/addBill")
    public String addBill(Bill bill, HttpSession session){
        bill.setCreatedBy(((User) session.getAttribute(Constants.USER_SESSION)).getId());
        bill.setCreationDate(new Date());
        boolean add = billServiceImpl.add(bill);
        if(add){
            return "redirect:/jsp/billQuery";
        }else{
            return "../../error";
        }
    }
    @RequestMapping("/deleteBill")
    @ResponseBody
    public String deleteBill(String billid){
        int delId = 0;
        try {
            delId = Integer.parseInt(billid);
        } catch (Exception e) {
            System.out.println("BillController->deleteBill->error");
        }
        HashMap<String, String> resultMap = new HashMap<String, String>();
        if (delId <= 0) {
            resultMap.put("delResult", "notexist");
        } else {
            if (billServiceImpl.deleteBillById(delId)) {
                resultMap.put("delResult", "true");
            } else {
                resultMap.put("delResult", "false");
            }
        }
        return JSONArray.toJSONString(resultMap);
    }
    // 通过id查询订单信息，在跳转到修改页面时携带数据，实现展示原数据然后修改的过程
    @RequestMapping("/toModifyPage")
    public String modifySave(String billid,Model model){
        if (!StringUtils.isNullOrEmpty(billid)) {
            //调用后台方法得到bill对象
            Bill bill = billServiceImpl.getBillByIdService(Integer.parseInt(billid));
            model.addAttribute("bill", bill);
            return "billModify";
        }else{
            return "../../error";
        }
    }
    // 订单修改页面，提交表单后修改数据库
    @RequestMapping("/billModifySave")
    public String modifySave(Bill bill,HttpSession session){
        bill.setProductCount(new BigDecimal(String.valueOf(bill.getProductCount())).setScale(2, BigDecimal.ROUND_DOWN));
        bill.setTotalPrice(new BigDecimal(String.valueOf(bill.getTotalPrice())).setScale(2, BigDecimal.ROUND_DOWN));
        bill.setModifyBy(((User) session.getAttribute(Constants.USER_SESSION)).getId());
        bill.setModifyDate(new Date());
        if (billServiceImpl.modify(bill)) {
            return "redirect:/jsp/billQuery";
        } else {
            return "billModify";
        }
    }
    @RequestMapping("/billView")
    public String billView(String billid,Model model){
        if (!StringUtils.isNullOrEmpty(billid)) {
            Bill bill = billServiceImpl.getBillByIdService(Integer.parseInt(billid));
            model.addAttribute("bill", bill);
            return "billView";
        }else{
            return "../../error";
        }
    }
}
